package com.sdgakj.utils;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 拦截器 统计dao service每个方法的执行时间
 * 
 * @author Hailong
 * 
 */
public class TimeWatchInterceptor implements MethodInterceptor {
	
	private static Logger logger = LoggerFactory.getLogger(TimeWatchInterceptor.class);

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		StopWatch clock = new StopWatch();
		clock.start(); // 计时开始
		Object result = invocation.proceed();
		clock.stop(); // 计时结束

		// 方法参数类型，转换成简单类型
		Class<?>[] params = invocation.getMethod().getParameterTypes();
		String[] simpleParams = new String[params.length];
		for (int i = 0; i < params.length; i++) {
			simpleParams[i] = params[i].getSimpleName();
		}

		logger.info("[" + invocation.getThis().getClass().getName() + "." + invocation.getMethod().getName() + "("
				+ StringUtils.join(simpleParams, ",") + ")]  invoke cost " + clock.getTime() + " ms");
		return result;
	}

}
